import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Card,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Dropdown,
  Image,
  Row,
  Col,
  Statistic
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  FileImageOutlined,
  CalendarOutlined,
  UserOutlined
} from '@ant-design/icons';
import useActivitiesStore from '../../store/activities/useActivitiesStore';
import ActivityForm from './ActivityForm';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;

const ActivitiesList = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [editingActivity, setEditingActivity] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [searchText, setSearchText] = useState('');
  
  const {
    activities,
    loading,
    filters,
    getActivities,
    deleteActivity,
    toggleActivityStatus,
    setFilters
  } = useActivitiesStore();

  useEffect(() => {
    getActivities(filters);
  }, []);

  // 状态标签配置
  const statusConfig = {
    published: { color: 'success', icon: <CheckCircleOutlined />, text: '已上线' },
    draft: { color: 'default', icon: <ClockCircleOutlined />, text: '草稿' },
    offline: { color: 'error', icon: <CloseCircleOutlined />, text: '已下线' }
  };

  // 统计数据
  const statistics = {
    total: activities.length,
    published: activities.filter(a => a.status === 'published').length,
    draft: activities.filter(a => a.status === 'draft').length,
    offline: activities.filter(a => a.status === 'offline').length
  };

  // 表格列配置
  const columns = [
    {
      title: '活动名称',
      key: 'name',
      width: 250,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 500, fontSize: 14 }}>{record.name}</span>
          <span style={{ color: '#999', fontSize: 12 }} className="line-clamp-2">
            {record.description}
          </span>
        </Space>
      ),
    },
    {
      title: 'Slug',
      dataIndex: 'slug',
      key: 'slug',
      width: 180,
      render: (slug) => (
        <Tag color="blue" style={{ fontSize: 12 }}>{slug}</Tag>
      ),
    },
    {
      title: '图片',
      dataIndex: 'images',
      key: 'images',
      width: 200,
      render: (images) => (
        <>
          {images && images.length > 0 ? (
            <Image.PreviewGroup>
              <Space size={8}>
                {images.slice(0, 3).map((url, index) => (
                  <Image
                    key={index}
                    width={40}
                    height={40}
                    src={url}
                    style={{ objectFit: 'cover', borderRadius: 4, cursor: 'pointer' }}
                  />
                ))}
                {images.length > 3 && (
                  <div style={{ 
                    width: 40, 
                    height: 40, 
                    background: '#f0f0f0', 
                    borderRadius: 4,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 12,
                    color: '#666',
                    fontWeight: 500
                  }}>
                    +{images.length - 3}
                  </div>
                )}
              </Space>
            </Image.PreviewGroup>
          ) : (
            <div style={{ 
              width: 40, 
              height: 40, 
              background: '#f0f0f0', 
              borderRadius: 4,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}>
              <FileImageOutlined style={{ color: '#999' }} />
            </div>
          )}
        </>
      ),
    },
    {
      title: '活动时间',
      key: 'time',
      width: 200,
      render: (_, record) => (
        <Space direction="vertical" size={4}>
          <Tag color="blue" style={{ margin: 0 }}>
            <CalendarOutlined style={{ marginRight: 4 }} />
            {dayjs(record.startTime).format('YYYY-MM-DD HH:mm')}
          </Tag>
          <Tag color="orange" style={{ margin: 0 }}>
            <CalendarOutlined style={{ marginRight: 4 }} />
            {dayjs(record.endTime).format('YYYY-MM-DD HH:mm')}
          </Tag>
        </Space>
      ),
    },
    {
      title: '获奖会员',
      dataIndex: 'winnerIds',
      key: 'winnerIds',
      width: 150,
      render: (winnerIds) => (
        winnerIds && winnerIds.length > 0 ? (
          <Space size={4} wrap>
            {winnerIds.slice(0, 2).map(id => (
              <Tag key={id} icon={<UserOutlined />} color="gold">
                {id}
              </Tag>
            ))}
            {winnerIds.length > 2 && (
              <Tag color="gold">+{winnerIds.length - 2}</Tag>
            )}
          </Space>
        ) : (
          <span style={{ color: '#999' }}>-</span>
        )
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = statusConfig[status];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 150,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => {
        const items = [
          {
            key: 'edit',
            label: '编辑',
            icon: <EditOutlined />,
            onClick: () => handleEdit(record),
          },
          {
            type: 'divider',
          },
        ];

        if (record.status === 'draft') {
          items.push({
            key: 'publish',
            label: '上线',
            icon: <CheckCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'published'),
          });
        } else if (record.status === 'published') {
          items.push({
            key: 'offline',
            label: '下线',
            icon: <CloseCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'offline'),
          });
        } else {
          items.push({
            key: 'publish',
            label: '重新上线',
            icon: <CheckCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'published'),
          });
        }

        items.push(
          { type: 'divider' },
          {
            key: 'delete',
            label: '删除',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => handleDelete(record),
          }
        );

        return (
          <Dropdown
            menu={{ items }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      },
    },
  ];

  // 处理编辑
  const handleEdit = (record) => {
    setEditingActivity(record);
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除活动"${record.name}"吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteActivity(record.id);
          message.success('删除成功');
        } catch {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理状态变更
  const handleStatusChange = async (id, status) => {
    try {
      await toggleActivityStatus(id, status);
      message.success('状态更新成功');
    } catch {
      message.error('状态更新失败');
    }
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    Modal.confirm({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个活动吗？`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          for (const id of selectedRowKeys) {
            await deleteActivity(id);
          }
          message.success('批量删除成功');
          setSelectedRowKeys([]);
        } catch {
          message.error('批量删除失败');
        }
      },
    });
  };

  // 处理状态筛选
  const handleStatusFilter = (status) => {
    getActivities({ status });
  };

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
    // 这里可以实现本地搜索或调用API
  };

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  // 过滤后的数据
  const filteredActivities = searchText
    ? activities.filter(activity =>
        activity.name.toLowerCase().includes(searchText.toLowerCase()) ||
        activity.description.toLowerCase().includes(searchText.toLowerCase())
      )
    : activities;

  return (
    <div className="p-6">
      {/* 统计卡片 */}
      <Row gutter={16} className="mb-6">
        <Col span={6}>
          <Card>
            <Statistic
              title="全部活动"
              value={statistics.total}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已上线"
              value={statistics.published}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="草稿"
              value={statistics.draft}
              valueStyle={{ color: '#666' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已下线"
              value={statistics.offline}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容区 */}
      <Card>
        <div className="mb-6 flex justify-between items-center">
          <Space size={12}>
            <Select
              value={filters.status}
              style={{ width: 120 }}
              onChange={handleStatusFilter}
            >
              <Option value="all">全部状态</Option>
              <Option value="published">已上线</Option>
              <Option value="draft">草稿</Option>
              <Option value="offline">已下线</Option>
            </Select>
            <Search
              placeholder="搜索活动名称或描述"
              allowClear
              onSearch={handleSearch}
              style={{ width: 250 }}
            />
            {selectedRowKeys.length > 0 && (
              <Button danger onClick={handleBatchDelete}>
                批量删除 ({selectedRowKeys.length})
              </Button>
            )}
          </Space>

          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingActivity(null);
              setModalVisible(true);
            }}
          >
            创建活动
          </Button>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredActivities}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            defaultPageSize: 10,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 活动表单弹窗 */}
      <Modal
        title={editingActivity ? '编辑活动' : '创建活动'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingActivity(null);
        }}
        footer={null}
        width={800}
        destroyOnClose
      >
        <ActivityForm
          activity={editingActivity}
          onSuccess={() => {
            setModalVisible(false);
            setEditingActivity(null);
            getActivities(filters);
          }}
          onCancel={() => {
            setModalVisible(false);
            setEditingActivity(null);
          }}
        />
      </Modal>
    </div>
  );
};

export default ActivitiesList;